package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.dtos.LikesBehaviorDto;
import com.heima.behavior.pojos.ApFollowBehavior;
import com.heima.behavior.pojos.ApLikesBehavior;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.constants.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.message.vos.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadLocal.ApUserThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    /**
     * 点赞行为
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //1.参数校验
        if(dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"该文章不存在");
        }

        //2.判断是否是登录用户还是游客身份
        ApUser apUser = ApUserThreadLocalUtil.getApUser();
        if(apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer userId = apUser.getId();
        if(userId==0){
            //3.如果是游客，则终止
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH,"游客身份，没有权限执行点赞");
        }

        //4.判断当前用户是否点赞过该文章
        String likeKey="USER_LIKES_"+dto.getArticleId();
        Boolean flag = redisTemplate.opsForHash().hasKey(likeKey, userId.toString());

        //5.如果点赞过，且正在进行的是点赞，则终止
        if(flag && dto.getOperation()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"当前用户已经点赞过该文章");
        }


        UpdateArticleMess mess=new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.LIKES);



        //6.如果点赞过，且正在执行的是取消点赞，则删除redis和mongo
        if(flag && dto.getOperation()==1){
            redisTemplate.opsForHash().delete(likeKey,userId.toString());

            mongoTemplate.remove(Query.query(
                    Criteria.where("userId").is(userId).and("articleId").is(dto.getArticleId())
            ), ApLikesBehavior.class);

            mess.setAdd(-1);
        }

        //7.如果没有点赞过，且正在进行的是点赞，则新增redis和mongo
        if(!flag && dto.getOperation()==0){
            redisTemplate.opsForHash().put(likeKey,userId.toString(),"1");
            ApLikesBehavior apLikeBehavior=new ApLikesBehavior();
            apLikeBehavior.setArticleId(dto.getArticleId());
            apLikeBehavior.setUserId(Long.valueOf(userId));
            apLikeBehavior.setCreatedTime(new Date());
            apLikeBehavior.setType((short) 0);
            mongoTemplate.save(apLikeBehavior);

            mess.setAdd(1);
        }

        //8.如果没有点赞过，且正在执行的是取消点赞,则终止
        if(!flag && dto.getOperation()==1){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"当前用户已经取消点赞执行过了");
        }


        //发送消息实现流式处理
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(mess));


        return ResponseResult.okResult("点赞|取消点赞完成");
    }
}
